<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /* 
            时间：O(N^2)
            空间：O(N)
        */
        function TreeNode(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new TreeNode(5)
        var b = new TreeNode(4)
        var c = new TreeNode(6)
        var d = new TreeNode(null)
        var e = new TreeNode(null)
        var f = new TreeNode(3)
        var g = new TreeNode(7)

        var h = new TreeNode(0)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g
        // 二叉搜索树就是左边的都比根节点小，右边的都比根节点大
        // 因为是有序的数组，找到中间值mid，[0, mid）都给到左子树，[mid+1, n.length - 1]都是右子树
        var sortedArrayToBST = function (nums) {
            function track (nums) {
                // 如果节点为空，也返回true
                if (nums.length === 0) return null

                let mid = Math.floor((0, nums.length - 1) / 2)
                let node = new TreeNode(nums[mid])

                let leftNums = nums.slice(0, mid)
                let rightNums = nums.slice(mid + 1)
                
                node.left = track(leftNums)
                node.right = track(rightNums)
                return node
            }
            return track(nums)
        };
        console.log(sortedArrayToBST([-10,-3,0,5,9]));
    </script>
</body>

</html>